{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e4afbbb6",
   "metadata": {},
   "source": [
    "# ScaNN\n",
    "\n",
    "ScaNN (Scalable Nearest Neighbors) is a method for efficient vector similarity search at scale.\n",
    "\n",
    "ScaNN includes search space pruning and quantization for Maximum Inner Product Search and also supports other distance functions such as Euclidean distance. The implementation is optimized for x86 processors with AVX2 support. See its [Google Research github](https://github.com/google-research/google-research/tree/master/scann) for more details.\n",
    "\n",
    "You'll need to install `langchain-community` with `pip install -qU langchain-community` to use this integration"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "082f593e",
   "metadata": {},
   "source": [
    "## Installation\n",
    "Install ScaNN through pip. Alternatively, you can follow instructions on the [ScaNN Website](https://github.com/google-research/google-research/tree/master/scann#building-from-source) to install from source."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a35e4f09",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install --upgrade --quiet  scann"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44bf38a8",
   "metadata": {},
   "source": [
    "## Retrieval Demo\n",
    "\n",
    "Below we show how to use ScaNN in conjunction with Huggingface Embeddings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "377bc723",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \\n\\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \\n\\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': 'state_of_the_union.txt'})"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_community.document_loaders import TextLoader\n",
    "from langchain_community.vectorstores import ScaNN\n",
    "from langchain_huggingface import HuggingFaceEmbeddings\n",
    "from langchain_text_splitters import CharacterTextSplitter\n",
    "\n",
    "loader = TextLoader(\"state_of_the_union.txt\")\n",
    "documents = loader.load()\n",
    "text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n",
    "docs = text_splitter.split_documents(documents)\n",
    "\n",
    "\n",
    "embeddings = HuggingFaceEmbeddings()\n",
    "\n",
    "db = ScaNN.from_documents(docs, embeddings)\n",
    "query = \"What did the president say about Ketanji Brown Jackson\"\n",
    "docs = db.similarity_search(query)\n",
    "\n",
    "docs[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9ad5b151",
   "metadata": {},
   "source": [
    "## RetrievalQA Demo\n",
    "\n",
    "Next, we demonstrate using ScaNN in conjunction with Google PaLM API.\n",
    "\n",
    "You can obtain an API key from https://developers.generativeai.google/tutorials/setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "fc27ad51",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chains import RetrievalQA\n",
    "from langchain_community.chat_models import google_palm\n",
    "\n",
    "palm_client = google_palm.ChatGooglePalm(google_api_key=\"YOUR_GOOGLE_PALM_API_KEY\")\n",
    "\n",
    "qa = RetrievalQA.from_chain_type(\n",
    "    llm=palm_client,\n",
    "    chain_type=\"stuff\",\n",
    "    retriever=db.as_retriever(search_kwargs={\"k\": 10}),\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "5b77f919",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The president said that Ketanji Brown Jackson is one of our nation's top legal minds, who will continue Justice Breyer's legacy of excellence.\n"
     ]
    }
   ],
   "source": [
    "print(qa.run(\"What did the president say about Ketanji Brown Jackson?\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "0c6deec6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The president did not mention Michael Phelps in his speech.\n"
     ]
    }
   ],
   "source": [
    "print(qa.run(\"What did the president say about Michael Phelps?\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8a49f4a6",
   "metadata": {},
   "source": [
    "## Save and loading local retrieval index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "6b7496b9",
   "metadata": {},
   "outputs": [],
   "source": [
    "db.save_local(\"/tmp/db\", \"state_of_union\")\n",
    "restored_db = ScaNN.load_local(\"/tmp/db\", embeddings, index_name=\"state_of_union\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
